package com.stars.easyms.datasource.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stars.easyms.base.util.JsonUtil;

import java.util.List;
import java.util.Map;

/**
 * <p>className: ParameterUtil</p>
 * <p>description: 参数工具类</p>
 *
 * @author guoguifang
 * @version 1.2.2
 * @date 2019-08-15 17:05
 */
@SuppressWarnings("unchecked")
public final class ParameterUtil {

    private static final int MAX_PARAMETER_STR_LENGTH = 1000;

    public static String getParameterString(Object parameterObject) {
        String parameterString = JsonUtil.toJSONString(parameterObject);
        // 若解析后的字符过长则把过长字符截断
        if (parameterString.length() > MAX_PARAMETER_STR_LENGTH) {
            try {
                JSONObject jsonObject = JSON.parseObject(parameterString);
                handleMapParameterString(jsonObject);
                parameterString = JSON.toJSONString(jsonObject);
            } catch (Exception e) {
                return parameterString.substring(0, MAX_PARAMETER_STR_LENGTH - 3) + "...";
            }
        }
        return parameterString;
    }

    private static void handleMapParameterString(Map map) {
        map.forEach((key, value) -> {
            if (value instanceof Map) {
                handleMapParameterString((Map) value);
            } else if (value instanceof List) {
                handleCollectionParameterString((List) value);
            } else if (value instanceof String){
                String str = (String) value;
                if (str.length() > MAX_PARAMETER_STR_LENGTH) {
                    map.put(key, str.substring(0, MAX_PARAMETER_STR_LENGTH - 3) + "...");
                }
            }
        });
    }

    private static void handleCollectionParameterString(List list) {
        for (int i = 0; i < list.size(); i++) {
            Object obj = list.get(i);
            if (obj instanceof String) {
                String str = (String) obj;
                if (str.length() > MAX_PARAMETER_STR_LENGTH) {
                    list.set(i, str.substring(0, MAX_PARAMETER_STR_LENGTH - 3) + "...");
                }
            }
        }
    }

    private ParameterUtil() {}
}